from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models.goods import GoodsCategory
from app.schemas.goods import GoodsCategoryCreate,GoodsCategoryUpdate


class CategoryController(CRUDBase[GoodsCategory, GoodsCategoryCreate, GoodsCategoryUpdate]):
    def __init__(self):
        super().__init__(model=GoodsCategory)

    async def get_tree(self):
        alls = await self.model.all().order_by("order")

        # 辅助函数，用于递归构建分类树
        def build_tree(parent_id):
            tree = []
            for item in alls:
                if item.parent_id == parent_id:
                    # 递归构建子分类
                    children = build_tree(item.id)
                    node = {
                        "id": item.id,
                        "key": item.id,
                        "name": item.name,
                        "label": item.name,
                        "desc": item.desc,
                        "order": item.order,
                        "parent_id": item.parent_id,
                    }
                    # 只有当 children 非空时才添加该字段
                    if children:
                        node["children"] = children
                    tree.append(node)
            return tree

        # 从顶级（parent_id=0）开始构建分类树
        tree = build_tree(0)
        return tree

    async def get_tree_ids(self, category_id:int):
        # 获取所有分类数据（已按order排序）
        all_categories = await self.model.all().order_by("order")

        # 将数据转换为字典形式以便快速查找
        categories_dict = {cat.id: cat for cat in all_categories}

        ids = []
        # 辅助函数：递归收集所有子分类ID
        def collect_child_ids(parent_id):
            # 添加当前父分类ID
            if parent_id in categories_dict:
                ids.append(parent_id)
                # 查找所有直接子分类
                for cat in all_categories:
                    if cat.parent_id == parent_id:
                        collect_child_ids(cat.id)  # 递归处理子分类

        collect_child_ids(category_id)
        return ids

    async def list_category(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('order')
        data = [await obj.to_dict() for obj in objs]
        return total, data

    async def get_category(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def create_category(self, obj_in: GoodsCategoryCreate):
        await self.create(obj_in=obj_in)
        return True

    async def update_category(self, obj_in: GoodsCategoryUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def delete_category(self, data_id: int):
        await self.remove(id=data_id)
        return True

    async def get_with_children(self,parent_id: int):
        menu = await category_controller.model.get(id=parent_id)
        menu_dict = await menu.to_dict()
        child_menus = await category_controller.model.filter(parent_id=parent_id).order_by("order")
        menu_dict["children"] = [await self.get_with_children(child.id) for child in child_menus]
        return menu_dict

category_controller = CategoryController()
